<!-- 产品管理 -->
<!-- <template>
  <div id="template">
    <page-main>
      <avue-crud v-model="Main_Form" :option="Main_Option" :data="Main_Data" :page.sync="Main_Page"
        :search.sync="Main_search" :table-loading="main_table_loading" ref="crud" @refresh-change="refreshChange"
        @search-change="searchChange" @reset-change="resetChange" @row-save="rowSave" @row-update="rowUpdate"
        @row-del="rowDel" @current-change="Main_currentChange" @size-change="Main_sizeChange">
        
        <template slot-scope="{ size, row, index}" slot="menu">
          
          <el-button :size="size" type="text" @click="viewResources(row, index)">查看资源</el-button>
        
        </template>

      </avue-crud>
    </page-main>

    <el-drawer title="商品资源" :visible.sync="drawerVisible" direction="rtl" size="80%" :destroy-on-close="true"
      :wrapperClosable="false" @close="drawerClose">
      <page-main title="以下为该商品挂载的文件资源">
        <avue-crud ref="crud" :table-loading="resource_table_loading" :option="Resource_Option" :data="Resource_Data"
          :page.sync="Resource_Page" :search.sync="Resource_search" @refresh-change="detailProductApiFunc"
          @search-change="Resource_searchChange" @reset-change="Resource_resetChange"
          @current-change="Resource_currentChange" @size-change="Resource_sizeChange">

          <template slot="menuLeft">
            <el-button size="small" type="success" @click="mountResources">挂载资源</el-button>
          </template>

          <template slot="menu" slot-scope="{ row, size }">
            <el-button :size="size" type="text" @click="rowResourceDel(row)">删除</el-button>
          </template>
        </avue-crud>
      </page-main>
    </el-drawer>

    <el-drawer title="选取资源" :visible.sync="selectVisible" direction="rtl" size="80%" :destroy-on-close="true"
      :wrapperClosable="false" @close="selectClose">
      <page-main title="可将以下资源挂载至商品，注意：主图、参数图、PDF皆只能选一份，以上资源类型已挂载将不可选中">
        <avue-crud ref="selectCrud" :table-loading="selectResource_table_loading" :option="SelectResources_Option"
          :data="SelectResources_Data" :page.sync="SelectResource_Page" :search.sync="SelectResource_search"
          @refresh-change="obtainResourceFunc" @selection-change="selectionChange"
          @search-change="SelectResource_searchChange" @reset-change="SelectResource_resetChange"
          @current-change="SelectResource_currentChange" @size-change="SelectResource_sizeChange">
          <template slot="menuLeft">
            <el-button size="small" type="success" @click="mountSelectedResources">挂载选中资源</el-button>
          </template>

          <template slot="tip">
            <el-tag type="danger" size="mini" style="margin-left: 15px;">{{
              `已选，主图：${selectTips.img || 0}，参数图：${selectTips.paramet || 0}，pdf：${selectTips.pdf || 0}，视频：${selectTips.mp4
              || 0}` }}</el-tag>
          </template>

        </avue-crud>
      </page-main>
    </el-drawer>


  </div>
</template>

<script>
import { Main_Option, Main_Data, Resource_Option, Resource_Data, SelectResources_Option, SelectResources_Data } from "./config";
import {
  queryProductApi,
  createProductApi,
  updateProductApi,
  deleteProductApi,
  detailProductApi,
  deleteMountProductApi,
  batchMountProductApi,
} from '@/api/productManage/index';
import {
  queryResourceApi,
} from '@/api/resource/index';
import {
  queryAllProductClassApi,
} from '@/api/productClass/index';

export default {
  data() {
    return {
      Main_Option,
      Main_Data,
      main_table_loading: false,
      Main_Form: {},
      Main_search: {},
      Main_Page: {
        currentPage: 1,
        pageSize: 10,
        total: 1,
      },
      drawerVisible: false,
      // 查看商品资源 - drawer
      Resource_Option,
      Resource_Data,
      Resource_Page: {
        currentPage: 1,
        pageSize: 10,
        total: 1,
      },
      Resource_search: {},
      Resource_Id: null,
      resource_table_loading: false,
      // ------------ 选取资源 drawer
      selectVisible: false,
      SelectResources_Option: SelectResources_Option(),
      SelectResources_Data,
      SelectResource_Page: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      SelectResource_search: {},
      selectResource_table_loading: false,
      selectTips: {
        img: 0,
        pdf: 0,
        mp4: 0,
        paramet: 0
      },
      checkedMap: [],
      // -------------------------
    };
  },
  created() {
    this.queryAllProductClassApiFunc();
  },
  mounted() {
    this.getHomePageInfoFunc();
  },
  methods: {
    // ---------------------------- 查看商品资源- drawer - start
    // 删除资源
    rowResourceDel(row) {
      console.log('row: ', row);
      if (!(this?.Resource_Id ?? null)) {
        this.$message.error("操作异常，请返回商品重试");
        return;
      }
      console.log(this.Resource_Id, '<------ Resource_Id');

      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteMountProductApiFunc({ id: this?.Resource_Id ?? '', resourceIds: [row.id] });
      }).catch(() => {
        this.$message.info('已取消');
      });
    },
    // 挂载资源
    mountResources() {
      this.drawerVisible = false;
      this.selectVisible = true;
      this.obtainResourceFunc();
    },
    // 关闭的回调
    drawerClose() { },
    async Resource_searchChange(params, done) {
      this.Resource_Page.currentPage = 1;
      this.Resource_Page.pageSize = 10;
      await this.detailProductApiFunc();
      done();
    },
    Resource_resetChange() {
      this.Resource_search = {};
    },
    // ---------------------------- 查看商品资源 - end
    // --------------------------------- 挂载资源
    mountSelectedResources() {
      if (this?.selectTips?.img === 0 && this?.selectTips?.pdf === 0 && this?.selectTips?.mp4 === 0 && this?.selectTips?.paramet === 0) {
        this.$message.error("请先选择资源！");
        return;
      }
      if (this?.selectTips?.img > 1) {
        this.$message.error("主图数量仅可选择1份！");
        return;
      }
      if (this?.selectTips?.pdf > 1) {
        this.$message.error("PDF数量仅可选择1份！");
        return;
      }
      if (this?.selectTips?.paramet > 1) {
        this.$message.error("参数图数量仅可选择1份！");
        return;
      }
      // console.log('mountSelectedResources: ', this.checkedMap);
      const list = this.checkedMap.map(item => item.id);
      this.batchMountProductApiFunc({ id: this?.Resource_Id, resourceIds: list });
    },
    // 关闭的回调
    selectClose() {
      this.checkedMap = [];
      this.selectTips.img = 0;
      this.selectTips.pdf = 0;
      this.selectTips.mp4 = 0;
      this.selectTips.paramet = 0;
    },
    // 选中回调
    selectionChange(value) {
      let img = 0, pdf = 0, mp4 = 0, paramet = 0;
      value && value.forEach(item => {
        if (item?.classificate === 1) pdf++;
        if (item?.classificate === 2) mp4++;
        if (item?.classificate === 3) img++;
        if (item?.classificate === 4) paramet++;
      });
      this.$set(this.selectTips, 'img', img);
      this.$set(this.selectTips, 'pdf', pdf);
      this.$set(this.selectTips, 'mp4', mp4);
      this.$set(this.selectTips, 'paramet', paramet);
      this.$set(this, 'checkedMap', JSON.parse(JSON.stringify(value)));
    },
    async SelectResource_searchChange(params, done) {
      this.SelectResource_Page.currentPage = 1;
      this.SelectResource_Page.pageSize = 10;
      await this.obtainResourceFunc();
      done();
    },
    SelectResource_resetChange() {
      this.SelectResource_search = {};
    },
    // ---------------------------------
    // 搜索事件
    async searchChange(params, done) {
      console.log(params, "< ---- form -- searchChange");
      await this.getHomePageInfoFunc();
      done();
    },
    // 查看商品资源
    viewResources(row) {
      this.drawerVisible = true;
      this.Resource_Id = row?.id ?? '';
      this.detailProductApiFunc();
    },
    // 重置
    resetChange() {
      this.Main_search = {};
    },
    // 刷新
    refreshChange() {
      this.Main_Page.currentPage = 1;
      this.getHomePageInfoFunc();
    },
    // main - 新增
    rowSave(form, done, loading) {
      const { title, label, details, sort } = form;
      this.createProductApiFunc({ title, label, details, sort }, done, loading);
    },
    // main - 编辑
    rowUpdate(row, index, done, loading) {
      const { id, title, label, details, sort } = row;
      this.updateProductApiFunc({ id, title, label, details, sort }, done, loading);
    },
    // main - 删除
    rowDel(row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteProductApiFunc({ id: row?.id ?? '' });
      }).catch(() => {
        this.$message.info('已取消');
      });
    },
    // main - currentChange
    Main_currentChange(val) {
      this.Main_Page.currentPage = val;
      this.getHomePageInfoFunc();
    },
    // main - sizeChange
    Main_sizeChange(val) {
      this.Main_Page.pageSize = val;
      this.Main_Page.currentPage = 1;
      this.getHomePageInfoFunc();
    },
    Resource_currentChange(val) {
      this.Resource_Page.currentPage = val;
      this.detailProductApiFunc();
    },
    Resource_sizeChange(val) {
      this.Resource_Page.pageSize = val;
      this.detailProductApiFunc();
    },
    SelectResource_currentChange(val) {
      this.SelectResource_Page.currentPage = val;
      this.obtainResourceFunc();
    },
    SelectResource_sizeChange(val) {
      this.SelectResource_Page.pageSize = val;
      this.obtainResourceFunc();
    },

    /**
     * @name requests
     * @author --h28
     */
    // 获取主页
    async getHomePageInfoFunc() {
      this.main_table_loading = true;
      const response = await queryProductApi({
        ...this.Main_search,
        currentPage: this?.Main_Page?.currentPage ?? 1,
        pageSize: this?.Main_Page?.pageSize ?? 10,
      }).catch(() => { });
      console.log('response: ', response);
      if (response?.code === 200) {
        this.Main_Data = response?.data?.records ?? [];
        this.Main_Page.total = response?.data?.total ?? 0;
      }
      this.main_table_loading = false;
    },
    // 新增
    async createProductApiFunc(data, done, loading) {
      const response = await createProductApi(data).catch(() => { });
      if (response?.code === 200) {
        this.$notify.success({ title: "提示", message: "新增成功", });
        this.Main_Page.currentPage = 1;
        this.getHomePageInfoFunc();
        done();
      }
      loading();
    },
    // 编辑
    async updateProductApiFunc(data, done, loading) {
      const response = await updateProductApi(data).catch(() => { });
      if (response?.code === 200) {
        this.$notify.success({ title: "提示", message: "编辑成功", });
        this.getHomePageInfoFunc();
        done();
      }
      loading();
    },
    // 删除
    async deleteProductApiFunc(data) {
      const loadding = this.$loading({
        lock: true,
        text: "加载中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const response = await deleteProductApi(data).catch(() => { });
      if (response?.code === 200) {
        this.$notify.success({ title: "提示", message: "删除成功", });
        this.Main_Page.currentPage = 1;
        this.getHomePageInfoFunc();
      }
      loadding.close();
    },
    // 获取资源数据
    obtainResourceFunc() {
      const that = this;
      return new Promise(async (resolve, reject) => {
        that.selectResource_table_loading = true;
        const response = await queryResourceApi({
          ...that.SelectResource_search,
          currentPage: that?.SelectResource_Page?.currentPage ?? 1,
          pageSize: that?.SelectResource_Page?.pageSize ?? 10,
        }).catch(() => { });
        console.log('response: ', response);
        if (response?.code === 200) {
          // 从 that.Products_Data 中提取 classificate 属性组成数组 list，然后通过 [...new Set(list)] 去重，得到不重复的分类选项数组。
          let list = that.Resource_Data && that.Resource_Data.map(item => item.classificate);
          list = [...new Set(list)];
          that.SelectResources_Option = SelectResources_Option(list);
          that.SelectResources_Data = response?.data?.records ?? [];
          that.$nextTick(() => {
            that.$refs.selectCrud.refreshTable();
          })
          that.SelectResource_Page.total = response?.data?.total ?? 0;
        }
        that.selectResource_table_loading = false;
        resolve();
      })
    },
    // 获取商品详情
    detailProductApiFunc() {
      const that = this;
      return new Promise(async (resolve, reject) => {
        if (!(that?.Resource_Id ?? null)) {
          resolve();
          return;
        };
        that.resource_table_loading = true;
        const response = await detailProductApi({
          ...that.Resource_search,
          id: that.Resource_Id,
          currentPage: that?.Resource_Page?.currentPage ?? 1,
          pageSize: that?.Resource_Page?.pageSize ?? 10,
        }).catch(() => { });
        if (response?.code === 200) {
          that.Resource_Data = response?.data?.records ?? [];
          that.Resource_Page.total = response?.data?.total ?? 0;
        }
        that.resource_table_loading = false;
        resolve();
      })
    },
    // 删除商品资源
    async deleteMountProductApiFunc(data) {
      const loadding = this.$loading({
        lock: true,
        text: "加载中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const response = await deleteMountProductApi({
        ...data,
      }).catch(() => { });
      if (response?.code === 200) {
        this.$message.success("删除成功");
        this.detailProductApiFunc();
      }
      loadding.close();
    },
    // 批量挂载商品资源
    async batchMountProductApiFunc(data) {
      const loadding = this.$loading({
        lock: true,
        text: "加载中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const response = await batchMountProductApi({
        ...data,
      }).catch(() => { });
      if (response?.code === 200) {
        this.$message.success("挂载成功");
        this.drawerVisible = true;
        this.selectVisible = false;
        this.detailProductApiFunc();
      }
      loadding.close();
    },
    // 获取商品分类
    async queryAllProductClassApiFunc() {
      const response = await queryAllProductClassApi().catch(() => { });
      if (response?.code === 200) {
        const list = response?.data ?? [];
        const map = list && list.map(item => {
          return {
            label: item?.label ?? '',
            value: item?.id ?? '',
          }
        });
        this.$set(this.Main_Option.column[2], 'dicData', map);
      }
    },
  },
};
</script> -->

<!-- <style>

  </style> -->
